<?php

/**
 * @name UserController
 * @desc 控制器
 */
class UserController extends AdminCommonController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        echo "Hello user";
        return false;
    }

    //会员列表
    public function listAction(){
       $params = $this->jsonData();

       $row = $params['pageSize'] ?? 12;
       $page = $params['page'] ?? 1;

       $userModel = UserModel::getSingleton();

       $cond = [];
       if(isset($params['user_id']) && $params['user_id']>0){
           $cond['u.user_id'] = trim($params['user_id']);
       }
       if(isset($params['moble']) && $params['moble'] != ''){
           $cond['u.moble'] = trim($params['moble']);
       }
       if(isset($params['date_s']) && $params['date_s'] != ''){
           $cond['u.create_time#>='] = $params['date_s'];
       }
       if(isset($params['date_e']) && $params['date_e'] != ''){
           $cond['u.create_time#<'] = $params['date_e'];
       }
       if(isset($params['user_type']) && $params['user_type'] != ''){
           $cond['u.user_type'] = $params['user_type'];
       }

       //非超级管理员
        $adminInfo = AdminModel::getSingleton()->find(['admin_id'=> $this->admin_info['admin_id']], 'admin_type,moble,user_id');
        if($adminInfo['admin_type']==1 || $adminInfo['admin_type'] == 2){
//            $userInfo = UserModel::getSingleton()->find(['moble'=> $adminInfo['moble']], 'user_id');
            $cond['u.refer_user_id|u.shop_user_id'] = $adminInfo['user_id'];
        }

       $list = $userModel->db
           ->field('u.*,uu.nick_name as r_nick_name')
           ->alias('u')
           ->join(['user', 'uu'], ['u.refer_user_id'=> 'uu.user_id'], 'left join')
           ->where_c($cond)
           ->order('u.user_id desc')
           ->limit(($page - 1) * $row, $row)
           ->select();

       $total = $userModel->db
           ->alias('u')
           ->join(['user', 'uu'], ['u.refer_user_id'=> 'uu.user_id'], 'left join')
           ->where_c($cond)
           ->count();

       $kpiLogModel = KpiLogModel::getSingleton();
       foreach($list as &$val){
            //可提现积分
            $lastKpilog = $kpiLogModel->db
                ->where(['user_id'=> $val['user_id']])
                ->order('create_time desc')
                ->find();
            if($lastKpilog){
                $val['point'] = $lastKpilog['point_after'];
            }
       }

       $data = [
           'list' => $list,
           'total' => intval($total),
           'current'   => intval($page),
           'pageSize'  => intval($row),
           'page'  => intval($page)
       ];

       $this->ajaxReturn(0, '', $data);
    }

    //会员升级
    public function upAction(){
        $params = $this->jsonData();
        $rule = [
            'user_id'	=> 'require|integer',
            'to_user_type'	=> 'require|integer|in:1,2'
        ];
        $msg = [
            'user_id.require' => '未获取到会员标识',
            'user_id.integer' => '会员标识错误',
            'to_user_type.require' => '必须指定升级类型',
            'to_user_type.integer' => '升级类型错误'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //用户信息
        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $params['user_id']]);

        if(!$userInfo['moble']){
            $this->ajaxReturn(400, '会员未绑定手机号，不能升级');
        }
        if($params['to_user_type'] == 1 && $userInfo['user_type'] != 0){
            $this->ajaxReturn(400, '会员身份错误');
        }
        if($params['to_user_type'] == 2 && ($userInfo['user_type']!=0 && $userInfo['user_type']!=1)){
            $this->ajaxReturn(400, '会员身份错误.');
        }
        if($userInfo['user_type'] == $params['to_user_type']){
            $this->ajaxReturn(400, '已经是该身份');
        }

        //验证开通资格
        $shop_up_money = intval(SysConfigModel::getConfByIndex('shop_up_money'));
        $shop_uptop_money = intval(SysConfigModel::getConfByIndex('shop_uptop_money'));

        if($params['to_user_type'] == 1 && $userInfo['use_money_total']< $shop_up_money) {
            $this->ajaxReturn(400, '未达到升级网店资格：'.$shop_up_money.'当前业绩：'.$userInfo['use_money_total']);
        }
        if($params['to_user_type'] == 2 && $userInfo['use_money_total']< $shop_uptop_money) {
            $this->ajaxReturn(400, '未达到升级实体店资格：'.$shop_uptop_money.'当前业绩：'.$userInfo['use_money_total']);
        }

        try{
            \Vendor\DB::startTrans();

            //新增/更新 店铺
            $shopModel = ShopModel::getSingleton();
            $shopInfo = $shopModel->find(['user_id'=> $userInfo['user_id']], 'shop_id');
            if(!$shopInfo){
                $shopData = [
                    'user_id'           => $params['user_id'],
                    'shop_type'         => $params['to_user_type'],
                    'shop_name'         => $userInfo['nick_name'].'的小店',
                    'shop_description'  => '促销活动火热进行中...',
                    'address'           => '',
                    'mobile'            => $userInfo['moble'],
                ];
                $res = $shopModel->add($shopData);
                $shopInfo['shop_id'] = $res;
            }else {
                $res = $shopModel->update(['shop_id'=> $shopInfo['shop_id']], ['shop_type'=> $params['to_user_type']]);
            }
            if(!$res){
                $this->ajaxReturn(400, '更新店铺失败');
            }

            //更新user表
            if(!$userModel->update(['user_id'=> $params['user_id']], ['user_type'=> $params['to_user_type'], 'shop_id'=> $shopInfo['shop_id']])){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '操作失败');
            }

            $adminModel = AdminModel::getSingleton();
            //查询管理员是否存在
            $adminInfo = $adminModel->find(['moble'=> $userInfo['moble']]);
            if($params['to_user_type'] == 1){
                $key = 'to_one_admin_id';
            }elseif($params['to_user_type'] == 2){
                $key = 'to_two_admin_id';
            }
            if($adminInfo){
                //更新管理身份
                $updateData = ['admin_type'=> $params['to_user_type'], $key=> $this->admin_info['admin_id']];
                if(!$adminModel->update(['moble'=> $userInfo['moble']], $updateData)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败.');
                }
            }else {
                $addData = [
                    'user_id'       => $userInfo['user_id'],
                    'admin_type'    => $params['to_user_type'],
                    'moble'         => $userInfo['moble'],
                    'password'      => md5(substr($userInfo['moble'], -6)),
                    'status'        => 1,
                    $key            => $this->admin_info['admin_id'],
                    'create_time'   => time()
                ];
                if(!$adminModel->add($addData)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败...', $adminModel->errMsg);
                }
            }

            \Vendor\DB::commit();
        }catch(Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '下单失败，请返回重试', $e->getMessage());
        }

        $this->ajaxReturn(0, '操作成功');
    }

    //会员充值
    public function chargeAction(){
        $params = $this->jsonData();
        $rule = [
            'user_id'	=> 'require|integer',
            'charge_num'	=> 'require|integer',
            'charge_amount' => 'require|integer',
        ];
        $msg = [
            'user_id.require' => '未获取到会员标识',
            'user_id.integer' => '会员标识错误',
            'charge_num.require' => '必须输入充值数量',
            'charge_num.integer' => '充值数量必须整数',
            'charge_amount.require' => '必须输入金额',
            'charge_amount.integer' => '充值金额整数',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $user_id = $params['user_id'];
        $charge_num = $params['charge_num'];
        $chage_amount = $params['charge_amount'];

        if($charge_num <= 0 || $chage_amount <= 0){
            $this->ajaxReturn(400, '充值数量或充值金额必须都大于0的整数');
        }

        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['user_id'=> $user_id]);

        try{
            \Vendor\DB::startTrans();

            //计算赠送积分
            $sysConfigModel = SysConfigModel::getSingleton();
            $scaleInfo = $sysConfigModel->getConfByIndex('charge_award_point');
            if(!$scaleInfo || !isset($scaleInfo['value'])){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '请先设置积分赠送比例');
            }
            $point_scale = intval($scaleInfo['value']);
            $point_scale_show = $point_scale*100;
            $point = $chage_amount * $point_scale;

            //新增充值记录
            $chargeLogModel = ChargeLogModel::getSingleton();
            $charge_id = $chargeLogModel->add([
                'user_id'   => $user_id,
                'coin'      => $charge_num,
                'point'     => $point,
                'money'     => $chage_amount,
                'point_scale'   => $point_scale,
                'released_coin' => 0,
                'released_point'    => 0
            ]);
            if(!$charge_id){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '充值失败1');
            }

            //充值总积分,冻结积分,充值币总数，冻结币数量 增加
            $res = $userModel->update(
                ['user_id'=> $user_id, 'point_charge_total'=> $userInfo['point_charge_total']],
                [
                    'point_charge_total'    => $userInfo['point_charge_total']+$point,
                    'f_point'               => $userInfo['f_point']+$point,
                    'coin_charge_total'     => $userInfo['coin_charge_total'] + $charge_num,
                    'f_coin'                => $userInfo['f_coin'] + $charge_num,
                    'money_total'                 => $userInfo['money_total'] + $chage_amount
                ]
            );
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '充值失败2');
            }
            $pointModel = PointLogModel::getSingleton();
            //积分入账记录
            $res = $pointModel->add([
                'charge_id' => $charge_id,
                'type'  => 1,
                'cate'  => 1,
                'user_id'=> $user_id,
                'from_user_id'  => 0,
                'amount_before' => $userInfo['point'],
                'amount'    => 0,
                'amount_after'  => $userInfo['point'],
                'f_amount_before' => $userInfo['f_point'],
                'f_amount'    => $point,
                'f_amount_after'  => $userInfo['f_point'] + $point,
                'description'   => '['.PointLogModel::$cateArr[1].']' . '增加冻结积分:' . $point . ',此次充值rmb：'. $chage_amount . ',赠送比例：'. $point_scale_show. '%',
            ]);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '充值失败3');
            }
            //币入账记录
            $coinModel = CoinLogModel::getSingleton();
            $res = $coinModel->add([
                'charge_id' => $charge_id,
                'type'  => 1,
                'cate'  => 1,
                'user_id'=> $user_id,
                'from_user_id'  => 0,
                'amount_before' => $userInfo['coin'],
                'amount'    => 0,
                'amount_after'  => $userInfo['coin'],
                'f_amount_before' => $userInfo['f_coin'],
                'f_amount'    => $charge_num,
                'f_amount_after'  => $userInfo['f_coin'] + $charge_num,
                'description'   => '['.CoinLogModel::$cateArr[1].']' . '增加冻结货币:' . $charge_num . ',此次充值rmb：'. $chage_amount,
            ]);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '充值失败4');
            }

            //构树苗赠送
            $allConfig = SysConfigModel::getAllConfig();
            $saplingCond = isset($allConfig['charge_award_sapling'])? intval($allConfig['charge_award_sapling']): 0;
            $sapling = 0;
            if($saplingCond>0){
                $sapling = floor($charge_num/$saplingCond)*$saplingCond;
            }
            if($sapling>0){
                //构树苗数量增加
                $res = $userModel->setInc(['user_id'=> $user_id], 'sapling', $sapling);
                if(!$res){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '充值失败5');
                }
                //构树苗记录增加
                $saplingModel = SaplingLogModel::getSingleton();
                $res = $saplingModel->add([
                    'charge_id' => $charge_id,
                    'type'  => 1,
                    'cate'  => 1,
                    'user_id'=> $user_id,
                    'from_user_id'  => 0,
                    'amount_before' => $userInfo['sapling'],
                    'amount'    => $sapling,
                    'amount_after'  => $userInfo['sapling']+$sapling,
                    'f_amount_before' => 0,
                    'f_amount'    => 0,
                    'f_amount_after'  => 0,
                    'description'   => '['.SaplingLogModel::$cateArr[1].']' . '增加可用树苗:' . $sapling . ',此次充值构树链数量：'. $charge_num,
                ]);
                if(!$res){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '充值失败6');
                }
            }

            \Vendor\DB::commit();
        }catch(\Yaf\Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '充值失败7');
        }

        //用户本身奖励（动态算力）
/*        $scale = $userModel->getAwardScale($amount);
        if($scale>0){
            $awardAmount = $amount*$scale;
            $userModel->setInc(['user_id'=> $user_id], 'coin', $awardAmount);
            //log
            $coinModel = CoinLogModel::getSingleton();
            $coinModel->add([
                'type'  => 1,
                'user_id'   => $user_id,
                'from_user_id'  => 0,       //0为平台送出
                'amount_before' => $userInfo['coin'],
                'amount'    => $awardAmount,
                'description'   => CoinLogModel::$descriptionType[4] . '奖励' . $amount,
                'amount_after'  => $userInfo['coin'] + $awardAmount,
            ]);
        }*/

        //父级执行奖励（充值账户本身不奖励）暂时取消充值奖励
//        $parent = $userModel->find(['user_id'=> $userInfo['refer_user_id']], 'user_id,refer_user_id,moble,f_coin,coin');
//        $this->awardcoin($parent, $charge_num, $userInfo);

        $this->ajaxReturn(0, '充值成功');
    }

    /**
     * 1.通过团队总充值业绩判断是否有充值奖励（业绩较低才有）
     * 2.再根据自身持币数量匹配赠送比例
     */
    private $pid;
    private function awardcoin($user, $amount, $chargeUser){
        $userModel = UserModel::getSingleton();
        $coinModel = CoinLogModel::getSingleton();
        $this->pid = $user['refer_user_id'];
        if($this->pid>0){
            $total_charge = 100000000;
            $minUser = [];
            //当前节点的子节点
            $child = $userModel->findAll(['refer_user_id'=> $user['user_id']], 'user_id');
            if(count($child) == 1){
                $minUser = $user;
            }else {
                $child1 = $userModel->getGroupTotalCharge($child[0]['user_id']);
                $child2 = $userModel->getGroupTotalCharge($child[1]['user_id']);
                if($child1 == $child2){
                    $minUser = $user;
                }else {
                    $minUser = $child1<$child2? $child[0]: $child[1];
                }
/*                foreach($child as $key=>$val){
                    $coin_charge_total = $userModel->getGroupTotalCharge($val['user_id']);
                    if( $coin_charge_total[0]['total'] < $total_charge ){
                        $total_charge = $coin_charge_total[0]['total'];
                        $minUser = $val;
                    }
                }*/
            }
            //如果团队金额低送出奖励
            if($minUser['user_id'] == $user['user_id']){
                //计算算力比例当天总和
                $awardAmountTotal = $coinModel->find(['user_id'=> $user['user_id'], 'cate#in'=> [4,6]], 'sum(amount) as total');
                $allconf = SysConfigModel::getAllConfig();
                $award_top = isset($allconf['charge_award_top'])?intval($allconf['charge_award_top']):0;

                //持有币=冻结货币+可用货币
                $canUseCoin = $user['coin'] + $user['f_coin'];
                //奖励比例(以持有币未基础数据)
                $scale = $userModel->getAwardScale($canUseCoin);
                if($scale>0 && $awardAmountTotal['total']< $award_top){
                    $awardAmount = $amount*$scale;//四舍五入
                    $userModel->setInc(['user_id'=> $user['user_id']], 'coin', $awardAmount);
                    //log
                    $coinModel->add([
                        'charge_id' => 0,
                        'type'  => 1,
                        'cate'  => 4,
                        'user_id'   => $user['user_id'],
                        'from_user_id'  => 0,       //0为平台送出
                        'amount_before' => $user['coin'],
                        'amount'    => $awardAmount,
                        'amount_after'  => $user['coin'] + $awardAmount,
                        'f_amount_before' => $user['f_coin'],
                        'f_amount'    => 0,
                        'f_amount_after'  => $user['f_coin'],
                        'description'   => '['.CoinLogModel::$cateArr[4].']' .'增加可用货币：'.$awardAmount.',(团队成员' . $chargeUser['moble'] . '充值'. $amount .')',
                    ]);
                }
            }
            //继续上一级
            $parent = $userModel->find(['user_id'=> $user['refer_user_id']], 'user_id, refer_user_id, moble, f_coin, coin');
            $this->awardcoin($parent, $amount, $chargeUser);
        }
    }

    //修改密码
    public function editpwdAction(){
        $params = $this->jsonData();
        $rule = [
            'opwd'	=> 'require',
            'passwd'	=> 'require|regex:login_pwd',
        ];
        $msg = [
            'opwd.require' => '必须输入原始密码',
            'passwd.require' => '必须输入新密码',
            'passwd.regex' => '登录密码必须6~16位，且必须数字与字母组合'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $adminModel = AdminModel::getSingleton();
        $adminInfo = $adminModel->find(['admin_id'=> $this->admin_info['admin_id']]);
//        print_r($this->admin_info);exit;
        if($adminInfo['password'] != md5($params['opwd'])){
            $this->ajaxReturn(400, '原始密码错误');
        }
        $res = $adminModel->update(
            ['admin_id'=> $this->admin_info['admin_id']],
            ['password'=> md5(trim($params['passwd'])), 'update_time'=> time()]
        );
        if(!$res) {
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, 'success');
    }

    //修改手机号
    public function editmobleAction(){
        $params = $this->jsonData();
        $rule = [
            'user_id'	=> 'require',
            'moble'	=> 'require|regex:moble',
        ];
        $msg = [
            'user_id.require' => '未获取用户ID，请刷新页面重试',
            'moble.require' => '必须输入新手机号',
            'moble.regex' => '手机号格式错误'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $userModel = UserModel::getSingleton();
        $exist = $userModel->find(['moble'=> $params['moble']], 'user_id');
        if($exist){
            $this->ajaxReturn(400, '手机号已注册');
        }

        $userInfo = $userModel->find(['user_id'=> $params['user_id']]);
        $temp = explode(',', $userInfo['history_moble']);
        array_push($temp, $userInfo['moble']);
        $upData = [
            'moble' => $params['moble'],
            'history_moble' => implode(',', $temp),
            'update_time'   => time()
        ];

        if(!$userModel->update(['user_id'=> $params['user_id']], $upData)){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }
}
